/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Cliente;

import Servidor.ChatMessage;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseListener;
import javax.swing.JButton;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.text.DefaultCaret;

/**
 *
 * @author daniel
 */
public class VentanaCliente extends javax.swing.JFrame implements ActionListener  {

    private static final long serialVersionUID = 1L;
	private boolean connected;
	private Client client;
        private String ipaddressServer ="127.0.0.1"; 
        private Integer port = 8085;
        private String username;
    

    public VentanaCliente() {
         super("Monitoreo");
        initComponents();
        myInitComponents();
       	setDefaultCloseOperation(EXIT_ON_CLOSE);
	setVisible(true);
    }
    
    

    
    public void actionPerformed(ActionEvent e) {

        if(connected) {
			client.sendMessage(new ChatMessage(ChatMessage.MESSAGE, campoTexto1.getText()));				
			campoTexto1.setText("");
			return;
		}	
	}
    
     public void mostrarMensaje(String mensaje) {
        areaTexto1.append(mensaje + "\n");
    }
    public void habilitarTexto(boolean editable) {
        campoTexto1.setEditable(editable);
    }
    
    void connectionFailed() {
                mostrarMensaje("Enter your username and press login");
                
		connected = false;
                logins.setEnabled(true);
	}
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jDesktopPane1 = new javax.swing.JDesktopPane();
        jInternalFrame3 = new javax.swing.JInternalFrame();
        campoTexto1 = new javax.swing.JTextField();
        jScrollPane2 = new javax.swing.JScrollPane();
        areaTexto1 = new javax.swing.JTextArea();
        logins = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setResizable(false);

        jDesktopPane1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        jInternalFrame3.setIconifiable(true);
        jInternalFrame3.setTitle("CHAT");
        jInternalFrame3.setAutoscrolls(true);
        jInternalFrame3.setVisible(true);

        campoTexto1.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        campoTexto1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                campoTexto1ActionPerformed(evt);
            }
        });

        areaTexto1.setEditable(false);
        areaTexto1.setColumns(20);
        areaTexto1.setRows(5);
        areaTexto1.setMaximumSize(new java.awt.Dimension(164, 94));
        areaTexto1.setName(""); // NOI18N
        jScrollPane2.setViewportView(areaTexto1);

        logins.setText("login");
        logins.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                loginsActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jInternalFrame3Layout = new javax.swing.GroupLayout(jInternalFrame3.getContentPane());
        jInternalFrame3.getContentPane().setLayout(jInternalFrame3Layout);
        jInternalFrame3Layout.setHorizontalGroup(
            jInternalFrame3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 299, Short.MAX_VALUE)
            .addGroup(jInternalFrame3Layout.createSequentialGroup()
                .addComponent(campoTexto1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(logins))
        );
        jInternalFrame3Layout.setVerticalGroup(
            jInternalFrame3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jInternalFrame3Layout.createSequentialGroup()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 267, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jInternalFrame3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(campoTexto1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(logins)))
        );

        jInternalFrame3.setBounds(593, 270, 310, 331);
        jDesktopPane1.add(jInternalFrame3, javax.swing.JLayeredPane.DEFAULT_LAYER);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jDesktopPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 890, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jDesktopPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 570, Short.MAX_VALUE)
        );

        setSize(new java.awt.Dimension(900, 600));
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void campoTexto1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_campoTexto1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_campoTexto1ActionPerformed

    private void loginsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loginsActionPerformed
      
			username = campoTexto1.getText().trim();
			this.jInternalFrame3.setTitle("CHAT : " + username);
			client = new Client(ipaddressServer, port, username, this);
			
			if(!client.start()) 
				return;
			campoTexto1.setText("");		
			connected = true;
			
			logins.setEnabled(false);
		
			campoTexto1.addActionListener(this);
                        
    }//GEN-LAST:event_loginsActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(VentanaCliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(VentanaCliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(VentanaCliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(VentanaCliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new VentanaCliente().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    public javax.swing.JTextArea areaTexto1;
    public javax.swing.JTextField campoTexto1;
    private javax.swing.JDesktopPane jDesktopPane1;
    private javax.swing.JInternalFrame jInternalFrame3;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JButton logins;
    // End of variables declaration//GEN-END:variables

    private void myInitComponents() {

        areaTexto1.setLineWrap(true);
        areaTexto1.append("enter your username and press login \n");
        logins.addActionListener(this);
        
       // Para que la ventana interna no se pueda mover, se le quita la accion del mouse click sobre la ventana
        for(MouseListener listener : ((javax.swing.plaf.basic.BasicInternalFrameUI) this.jInternalFrame3.getUI()).getNorthPane().getMouseListeners()){
        ((javax.swing.plaf.basic.BasicInternalFrameUI) this.jInternalFrame3.getUI()).getNorthPane().removeMouseListener(listener);
        }
       // Para poder ver siempre los nuevos mensajes.
        DefaultCaret caret = (DefaultCaret)areaTexto1.getCaret();  
        caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);  
            
        
    }
    
}
